package com.demoai.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AIService {

    @Autowired
    private KnowledgeService knowledgeService;

    @Value("${deepseek.api.key}")
    private String apiKey;

    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    @Autowired
    private RestTemplate restTemplate;

    // 本地知识库查询（保持原样）
    public String getLocalAnswer(String question) {
        return knowledgeService.searchKnowledge(question);
    }

    // 调用DeepSeek API
// 请求体构造方法调整
    private Map<String, Object> createRequestBody(String question) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat"); // 必须指定模型
        requestBody.put("temperature", 0.7);

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of(
                "role", "user",
                "content", question // 直接使用原始问题，prompt优化前置
        ));
        requestBody.put("messages", messages);

        return requestBody;
    }

    // 调用方法修改
    public String getAIAnswer(String question) {
        try {
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(
                    createRequestBody(question),
                    createHeaders()
            );
            ResponseEntity<Map> response = restTemplate.exchange(
                    API_URL,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            return parseResponse(response.getBody());
        } catch (Exception e) {
            return "接口调用失败：" + e.getMessage();
        }
    }

    // 专用Header构造方法
    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey); // 使用标准Bearer认证
        return headers;
    }

    // 标准化响应解析
    private String parseResponse(Map<String, Object> responseBody) {
        try {
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
            Map<String, String> message = (Map<String, String>) choices.get(0).get("message");
            return message.get("content");
        } catch (Exception e) {
            return "响应解析失败：" + responseBody.getOrDefault("error", "未知错误");
        }
    }
}